//
//  BSDownloadImageTool.m
//  Baisijie
//
//  Created by 王建伟 on 2017/3/24.
//  Copyright © 2017年 RangGuangyu. All rights reserved.
//

#import "BSDownloadImageTool.h"
#import <SDImageCache.h>
#import <AFNetworkReachabilityManager.h>
#import "UIImage+Extension.h"

@implementation BSDownloadImageTool

+ (void)bs_showImageInImageView:(UIImageView *)imageView bigImageUrl:(NSString *)bigImageUrl thumbnailImageUrl:(NSString *)thumbnailImageUrl useTop:(BOOL)isUseTop progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock {
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    //从沙盒获取图片
    UIImage *bigImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:bigImageUrl];
    if (bigImage) { //有大图
        [imageView sd_setImageWithURL:[NSURL URLWithString:bigImageUrl] placeholderImage:nil options:0 progress:progressBlock completed:completedBlock];
    } else { //无大图
        UIImage *thumbnailImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:thumbnailImageUrl];
        if (mgr.isReachableViaWiFi) { //WiFi下载大图
            [imageView sd_setImageWithURL:[NSURL URLWithString:bigImageUrl] placeholderImage:nil options:0 progress:progressBlock completed:completedBlock];
        } else if (mgr.isReachableViaWWAN) { //手机网络
            if (thumbnailImage) {   //有小图
                [imageView sd_setImageWithURL:[NSURL URLWithString:thumbnailImageUrl] placeholderImage:nil options:0 progress:progressBlock completed:completedBlock];
            } else { //无小图下载小图
                [imageView sd_setImageWithURL:[NSURL URLWithString:thumbnailImageUrl] placeholderImage:nil options:0 progress:progressBlock completed:completedBlock];
            }
        } else {   //没有网络
            if (thumbnailImage) {   //有小图
                [imageView sd_setImageWithURL:[NSURL URLWithString:thumbnailImageUrl] placeholderImage:nil options:0 progress:progressBlock completed:completedBlock];
            } else { //无小图下载小图
                imageView.image = nil;
                if (progressBlock) {
                    progressBlock(1, 1);
                }
                if (completedBlock) {
                    completedBlock(nil, nil, 0, [NSURL URLWithString:thumbnailImageUrl]);
                }
            }
        }
    }
}

@end
